package com.java2007.dao.impl;

import com.java2007.dao.FoodTypeDao;
import com.java2007.pojo.FoodType;
import com.java2007.util.JdbcUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import java.sql.SQLException;
import java.util.List;

/**
 * 菜类别持久层接口实现
 */
public class FoodTypeDaoImpl implements FoodTypeDao {
    /**
     * 查询全部菜类别
     * @return
     * @throws SQLException
     */
    @Override
    public List<FoodType> selectAll() throws SQLException {
        //获取执行对象
        QueryRunner runner = new QueryRunner(JdbcUtil.getDataSource());
        String sql="SELECT `type_id` typeId ,`type_name` typeName FROM`t_food_type`";
        return  runner.query(sql, new BeanListHandler<FoodType>(FoodType.class));
    }

    /**
     * 根据名字查询菜类别
     * @param foodTypeName
     * @return
     * @throws SQLException
     */
    @Override
    public List<FoodType> findByFoodTypeName(String foodTypeName) throws SQLException {
        QueryRunner runner = new QueryRunner(JdbcUtil.getDataSource());
        String sql="SELECT `type_id` typeId ,`type_name` typeName FROM`t_food_type`WHERE `type_name` LIKE ?";
        return runner.query(sql, new BeanListHandler<FoodType>(FoodType.class),foodTypeName);
    }

    /**
     * 根据ID删除菜类别
     * @param typeId
     * @return
     * @throws SQLException
     */
    @Override
    public int deleteByFoodTypeId(Integer typeId) throws SQLException {
        QueryRunner runner = new QueryRunner();
        String sql="DELETE FROM `t_food_type` WHERE `type_id` = ?";
        return runner.update(JdbcUtil.getConnection(),sql,typeId);
    }

    /**
     * 根据菜类别名添加
     * @param typeName
     * @return
     * @throws SQLException
     */
    @Override
    public int saveByFoodTypeName(String typeName) throws SQLException {
        QueryRunner runner = new QueryRunner();
        String sql="INSERT INTO `t_food_type`(`type_name`)VALUES(?)";
        return runner.update(JdbcUtil.getConnection(),sql,typeName);
    }

    @Override
    public FoodType findByFoodTypeId(int typeId) throws SQLException {
        QueryRunner runner = new QueryRunner(JdbcUtil.getDataSource());
        String sql="SELECT `type_id` typeId ,`type_name` typeName FROM`t_food_type`WHERE`type_id`=?";
        return runner.query(sql, new BeanHandler<FoodType>(FoodType.class),typeId);
    }

    @Override
    public int updata(FoodType foodType) throws SQLException {
        QueryRunner runner = new QueryRunner();
        String sql="UPDATE t_food_type SET type_name = ? WHERE type_id = ?";
        return runner.update(JdbcUtil.getConnection(),sql,foodType.getTypeName(),foodType.getTypeId());
    }


//    public static void main(String[] args) throws SQLException {
//        FoodTypeDao ftd = new FoodTypeDaoImpl();
//        FoodType byFoodTypeId = ftd.findByFoodTypeId(12);
//        System.out.println(byFoodTypeId);
//
//    }
}
